<?php
/*
 * @Author: ZhaohangYang <yangzhaohang@comsenz-service.com>
 * @Date: 2021-06-23 16:58:47
 * @Description: 伙伴智慧大客户研发部
 */
namespace App\ModelsHuoban;

use Huoban\Huoban;
use Illuminate\Support\Facades\Log;

class HuobanAction
{
    public $huoban, $huobanModels;
    public static $huobanItem;

    public function __construct($config)
    {
        $this->huoban     = new Huoban($config);
        self::$huobanItem = $this->huoban->make('item');
    }

    /**
     * 效验伙伴请求返回结果
     *
     * @param [type] $response
     * @param string $location
     * @return void
     */
    public function verifyHuobanResponse($response, $location = '', $type = 'throw', $supplementary = '')
    {
        if (isset($response['code'])) {
            $message = $response['message'] ?? '未知错误信息';
            $message .= PHP_EOL . $supplementary;

            if ('log' == $type) {
                Log::error($location . PHP_EOL . $message);
            } else {
                throw new \Exception($location . $message, 10001);
            }
        }
    }

    /**
     * 收集并回写错误信息
     *
     * @param [type] $table_alias
     * @param [type] $message
     * @param [type] $item_id
     * @return void
     */
    public function collectError($table_alias, $message, $item_id = null)
    {
        if ($item_id) {
            $body = [
                'fields' => [
                    'F::' . $table_alias . '.app_error_message' => $message,
                ],
            ];
            self::$huobanItem->update($item_id, $body);
        }

    }

}
